package org.octopus.data.desensitized.core.strategy;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import lombok.extern.slf4j.Slf4j;
import org.octopus.data.desensitized.core.annotation.DesensitizedRule;

/**
 * @author lemon
 * @date 2021/8/27 11:14
 */
@Slf4j
public abstract class AbstractDesensitizedStrategy<T> implements DesensitizedStrategy<T> {

    private final Class<T> dataType;

    public AbstractDesensitizedStrategy() {
        Type type = this.getClass().getGenericSuperclass();

        if (type instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) type;
            dataType = (Class<T>) parameterizedType.getActualTypeArguments()[0];
        } else {
            dataType = null;
        }

        log.info("Class[{}] the actual parameter type is {}", this.getClass(), dataType);
    }

    @Override
    public final Class<T> supportDataType() {
        return this.dataType;
    }

    /**
     * 数据脱敏
     *
     * @param original
     * @return
     */
    @Override
    public final T convert(T original, DesensitizedRule desensitizedRule) {
        if (original == null) {
            return null;
        }

        if (!desensitizedRule.isEnable()) {
            return original;
        }

        return this.doConvert(original, desensitizedRule);
    }

    /**
     * 数据脱敏
     *
     * @param original
     * @param desensitizedRule
     * @return
     */
    abstract protected T doConvert(T original, DesensitizedRule desensitizedRule);
}
